#!/usr/bin/env python
# -*- coding: UTF-8 -*-

import sys
##sys.path.append("/home/aoting/.local/lib/python2.7/site-packages")
reload(sys)
sys.setdefaultencoding('utf8')

import rospy
import json
from flask import Blueprint,request, Response
import os,json
import rospy
import numpy as np

from parser.bulkdata_parser import BulkdataParser
from tool.common import *

bulkdata_parser = BulkdataParser()
bulkdata_server = Blueprint("/bulkdata",__name__)

import cv2
from io import BytesIO
from PIL import Image
import base64

#---------------------------------#
#******#   flask-网络端口验证   #******#
#---------------------------------#
@bulkdata_server.before_request
def before():
    res_data = before_user(request)
    if res_data:
        return Response(json.dumps(res_data),  mimetype='application/json')



#---------------------------------#
    #******#   POST   #******#
#---------------------------------#
# 连接测试
# req: 
# res: {'code': 0, 'ret': 'ok'}
@bulkdata_server.route('/test',methods=['POST','GET'])
def TestConnection():
    data={};data["code"]=0;data["msg"]="success"
    return Response(json.dumps(data), mimetype='application/json')

#---------------------------------#
    #******#   POST   #******#
#---------------------------------#
# 地图图片下载获取
# req: 
# res: 
@bulkdata_server.route('/map/Download/<map_name>')
def DownloadMap(map_name):
    try:
        rospy.loginfo("[bulkdata_server]requst map name: {}, current map name: {}".format(map_name,bulkdata_parser.GetCurMapName()))
        
        map_path = os.path.join(bulkdata_parser.GetMapDatabasePath(),map_name)
        rospy.loginfo("[bulkdata_server]map_path: {}".format(map_path))
        map_file_path = os.path.join(map_path, "map.png")

        # 新增尝试3次获取地图图片数据，每次1秒
        for i in range(3):
            if not os.path.isdir(map_path) or not os.path.exists(map_file_path):
                time.sleep(1)

        if not os.path.isdir(map_path):
            data={};data["code"]=-1;data["msg"]="map name error!"
            return Response(json.dumps(data),  mimetype='application/json')

        # map_file = file(os.path.join(map_path,"map.png"))
        
        with open(map_file_path, 'rb') as map_file:
            image_data = map_file.read()
        
        # 创建 Response 对象并设置属性
        response = Response(image_data, mimetype="image/png")
        response.content_length = len(image_data)
        
        # return Response(map_file, mimetype="image/png")
        return response

    except Exception as err:
        rospy.logerr("[bulkdata_server]Failed to download map image: {}".format(str(err)))
        return

#---------------------------------#
    #******#   POST   #******#
#---------------------------------#
# 建图过程中实时地图上传
# req: 
# res: 
@bulkdata_server.route('/map/CloudImgUpdate',methods=['POST','GET'])
def UpdateMapCloudImg():
    data={};data["code"]=0;data["msg"]="success"
    try:
        res_header={}
        map_index_info = bulkdata_parser.GetMapIndex()
        if map_index_info and "map_png_str" in map_index_info and "data" in map_index_info:

            if "data" in map_index_info:
                res_header["map_info"]=json.dumps(map_index_info["data"])
                res_header["Access-Control-Expose-Headers"]="map_info"
            else:
                data["position_x"] = 0.0  # 没有建图的时候提供当前地图数据 20230824-dw.liu
                data["position_y"] = 0.0
                data["width"] = 0
                data["height"] = 0
                data["extend_top_bottom"] = 0
                data["extend_left_right"] = 0
                return Response(json.dumps(data), mimetype='application/json') 
                
            if map_index_info["map_png_str"]:
                return Response(map_index_info["map_png_str"], mimetype="image/png"),res_header
        else:
            raise Exception("map_index_info error!")                  
    except Exception as err:
        rospy.logerr("[bulkdata_server]Failed to update map image: {}".format(str(err)))
        data["code"]=-1
        data["msg"]=str(err)
        return Response(json.dumps(data), mimetype='application/json') 

#---------------------------------#
    #******#   POST   #******#
#---------------------------------#
# 建图过程中实时地图信息上传
# req: 
# res: 
@bulkdata_server.route('/map/CloudInfoUpdate',methods=['POST','GET'])
def UpdateMapCloudInfo():
    data={};data["code"]=0;data["msg"]="success"
    try:
        if  bulkdata_parser.IsMapCreating():
            # 建图
            data["position_x"] = bulkdata_parser.map_originx
            data["position_y"] = bulkdata_parser.map_originy
            data["width"] = bulkdata_parser.map_width
            data["height"] = bulkdata_parser.map_height
        else:
            # 没有建图或没有地图的时候也能够，雷达过滤  20231116-dw.liu
            data["position_x"] = bulkdata_parser._map_info_originx
            data["position_y"] = bulkdata_parser._map_info_originy
            data["width"] = bulkdata_parser._map_info_width
            data["height"] = bulkdata_parser._map_info_height
            data["resolution"] = bulkdata_parser._map_info_resolution

        return Response(json.dumps(data), mimetype='application/json') 
    except Exception as err:
        rospy.logerr(str(err))
        data["position_x"] = 0.0
        data["position_y"] = 0.0
        data["width"] = 0
        data["height"] = 0
        data["code"]=-1
        #data["ret"]="fail"
        data["msg"]=str(err)
        return Response(json.dumps(data), mimetype='application/json') 
    

#---------------------------------#
    #******#    GET    #******#
#---------------------------------#
# 机器清扫的任务路线
# res: {'code': 0, 'ret': 'success', 'map_name':""}
@bulkdata_server.route('/task_history/png')
def Post_GetTaskHistoryPng():
    import os
    data={};data["code"]=0;data["msg"]="success"
    try:
        
            '''file_path = bulkdata_parser.GetTaskPathMapcacheDir()
            # if os.path.exists(file_path):
            map_file = file(file_path)
        
            data_xy ={}
            data_xy["position_x"] = bulkdata_parser.task_path_map_originx
            data_xy["position_y"] = bulkdata_parser.task_path_map_originy
            
            return Response(map_file, mimetype="image/png"),data_xy'''
    
            file_path = bulkdata_parser.GetTaskPathMapcacheDir()
            # 加上锁，避免出现对文件读写同时进行，同时进行会导致显示效果不好
            if not bulkdata_parser.IsCleanTaskMapUpdating() and os.path.exists(file_path): 
                # file_path="/home/aoting/task_track.png"
                map_file = file(file_path)

                data_xy ={}
                data_xy["position_x"] = bulkdata_parser.task_path_map_originx
                data_xy["position_y"] = bulkdata_parser.task_path_map_originy
                data_xy["Access-Control-Expose-Headers"] = "position_x,position_y"
                data_xy["Content-Length"] = os.path.getsize(file_path)
                
                return Response(map_file, mimetype="image/png"),data_xy
            else:
                return Response(json.dumps(data), mimetype='application/json') 

    except Exception as err:
        rospy.logerr("[bulkdata_server]Failed to update map image: {}".format(str(err)))
        data["code"]=-1
        #data["ret"]="fail"
        data["msg"]=str(err)
        return Response(json.dumps(data), mimetype='application/json') 
